package com.coscoshipping.rams.demo.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONArray;
import com.coscoshipping.rams.demo.pojo.vo.BusinessSalesVO;
import com.coscoshipping.rams.demo.pojo.vo.TicketSalesVO;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * HTTP 请求工具类
 */
public class HttpUtils {




    /**
     * 营业销售统计
     * 发送 POST 请求并解析响应值
     *
     * @return          解析后的 BusinessSalesVO 列表
     */
    public static List<BusinessSalesVO> businessSales(LocalDateTime tabulationTime) {

        // 定义日期时间格式化模式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将 LocalDateTime 转换为指定格式的字符串
        String formattedDate = tabulationTime.format(formatter);

        // 示例调用
        String url = "http://192.168.3.81:9000/api/report/searchFilter";

        // 请求头
        JSONObject headers = new JSONObject();
        headers.put("accesskey", "a49ea513e1008a993ea79635ebc78c95");
        headers.put("sign", "3297EA978302E049AE5878EF68472D73");
        headers.put("timestamp", "1744874653577");

        // 请求体
        JSONObject body = new JSONObject();
        body.put("id", 50);
        body.put("shareMode", 1);
        body.put("reportType", 0);
        JSONObject params = new JSONObject();
        params.put("serviceCode", "liupanshan");
        params.put("timeStamp", "1744874235418");
        params.put("corpCodes", "0001/73785019/");
        params.put("pageIndex", 1);
        params.put("pageSize", 50);
        params.put("beginTradeDate", formattedDate);
        params.put("endTradeDate", formattedDate);
        params.put("beginTradeDateendTradeDate", formattedDate);
        params.put("begin_date", formattedDate);
        params.put("end_date", formattedDate);
        params.put("begin_dateend_date", formattedDate);
        params.put("wItemName", null);
        params.put("id", 50);
        params.put("shareMode", 1);
        body.put("params", params);
        body.put("reportColumnDisplayList", new JSONObject[] {});

        // 创建 POST 请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json");

        // 添加请求头
        if (headers != null) {
            for (String key : headers.keySet()) {
                request.header(key, headers.getStr(key));
            }
        }

        // 设置请求体
        if (body != null) {
            request.body(body.toString());
        }

        // 发送请求并获取响应
        HttpResponse response = request.execute();
        String responseBody = response.body();

        // 解析响应数据
        JSONObject jsonResponse = new JSONObject(responseBody);

        // 修改: 将 getJSONArray 改为 getJSONObject
        JSONObject resultObject = jsonResponse.getJSONObject("result");
        if (resultObject == null) {
            throw new RuntimeException("响应中未找到有效的 'result' 对象");
        }

        JSONArray reportSearchList = resultObject.getJSONArray("reportSearchList");
        if (reportSearchList == null) {
            throw new RuntimeException("响应中未找到 'reportSearchList' 对象");
        }

        // 修改: 检查 reportSearchList 是否包含 rows 数组
        JSONObject rowsObject = (JSONObject) reportSearchList.get(0);

        JSONArray rows = rowsObject.getJSONArray("rows");

        // 将 rows 数组映射为 List<BusinessSalesVO>
        List<BusinessSalesVO> businessSalesList = new ArrayList<>();
        for (int i = 0; i < rows.size(); i++) {
            JSONObject row = rows.getJSONObject(i);
            BusinessSalesVO vo = new BusinessSalesVO();
            vo.setTabulationTime(tabulationTime);
            vo.setItemname(row.getStr("itemname"));
            vo.setGroupname(row.getStr("groupname"));
            vo.setTodaySumAfter(new BigDecimal(row.getStr("today_sum_after")));
            vo.setTodaySum(new BigDecimal(row.getStr("today_sum")));
            vo.setMonthSum(new BigDecimal(row.getStr("month_sum")));
            businessSalesList.add(vo);
        }

        return businessSalesList;
    }


    /**
     * 票型销售统计
     * 发送 POST 请求并解析响应值
     *
     * @param tabulationTime 指定日期
     * @return 解析后的 TicketSalesVO 列表
     */
    public static List<TicketSalesVO> ticketSales(LocalDateTime tabulationTime) {
        // 定义日期时间格式化模式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 计算当天的开始时间和结束时间
        String beginTime = tabulationTime.toLocalDate().atStartOfDay().format(formatter);
        String endTime = tabulationTime.toLocalDate().atTime(23, 59, 59).format(formatter);

        // 示例调用
        String url = "http://192.168.3.81:9000/api/report/searchFilter";

        // 请求头
        JSONObject headers = new JSONObject();
        headers.put("accesskey", "a49ea513e1008a993ea79635ebc78c95");
        headers.put("sign", "3297EA978302E049AE5878EF68472D73");
        headers.put("timestamp", "1744874653577");

        // 请求体
        JSONObject body = new JSONObject();
        body.put("id", 53);
        body.put("shareMode", 1);
        body.put("reportType", 0);
        JSONObject params = new JSONObject();
        params.put("serviceCode", "liupanshan");
        params.put("timeStamp", "1744874235418");
        params.put("corpCodes", "0001/73785019/");
        params.put("pageIndex", 1);
        params.put("pageSize", 50);
        params.put("beginTime", beginTime);
        params.put("endTime", endTime);
        params.put("beginTimeendTime", endTime);
        params.put("groups", "");
        params.put("ticketIds", "");
        params.put("client_type", "");
        params.put("ticketKinds", "");
        params.put("tradetype", "");
        params.put("id", 53);
        body.put("params", params);
        body.put("reportColumnDisplayList", new JSONObject[] {});

        // 创建 POST 请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json");

        // 添加请求头
        if (headers != null) {
            for (String key : headers.keySet()) {
                request.header(key, headers.getStr(key));
            }
        }

        // 设置请求体
        if (body != null) {
            request.body(body.toString());
        }

        // 发送请求并获取响应
        HttpResponse response = request.execute();
        String responseBody = response.body();

        // 解析响应数据
        JSONObject jsonResponse = new JSONObject(responseBody);

        // 检查 result 对象是否存在
        JSONObject resultObject = jsonResponse.getJSONObject("result");
        if (resultObject == null) {
            throw new RuntimeException("响应中未找到有效的 'result' 对象");
        }

        // 获取 reportSearchList
        JSONArray reportSearchList = resultObject.getJSONArray("reportSearchList");
        if (reportSearchList == null) {
            throw new RuntimeException("响应中未找到 'reportSearchList' 对象");
        }

        // 获取 rows 数组
        JSONObject rowsObject = (JSONObject) reportSearchList.get(0);
        JSONArray rows = rowsObject.getJSONArray("rows");
        

        // 将 rows 数组映射为 List<TicketSalesVO>
        List<TicketSalesVO> ticketSalesList = new ArrayList<>();
        for (int i = 0; i < rows.size(); i++) {
            JSONObject row = rows.getJSONObject(i);
            TicketSalesVO vo = new TicketSalesVO();
            vo.setSalesDate(tabulationTime.toLocalDate());
            vo.setTicketTypeCategory(row.getStr("票型分类"));
            vo.setTicketType(row.getStr("票型"));
            vo.setCustomerType(row.getStr("客户类型"));
            vo.setTransactionType(row.getStr("交易类型"));
            vo.setTicketVariety(row.getStr("票种"));

            // 修改: 添加空值检查，避免 NullPointerException
            String unitPriceStr = row.getStr("单价");
            vo.setUnitPrice(unitPriceStr != null ? new BigDecimal(unitPriceStr) : BigDecimal.ZERO);

            String quantityStr = row.getStr("数量");
            vo.setQuantity(quantityStr != null ? Integer.parseInt(quantityStr) : 0);

            String amountStr = row.getStr("金额");
            vo.setAmount(amountStr != null ? new BigDecimal(amountStr) : BigDecimal.ZERO);

            String afterTaxAmountStr = row.getStr("税后金额");
            vo.setAfterTaxAmount(afterTaxAmountStr != null ? new BigDecimal(afterTaxAmountStr) : BigDecimal.ZERO);

            ticketSalesList.add(vo);
        }

        return ticketSalesList;
    }

    public static void main(String[] args) {

        String dateStr = "2025-04-02";
        LocalDateTime localDateTime = DateUtil.parse(dateStr).toLocalDateTime();

        // 营业销售统计
//        List<BusinessSalesVO> response = businessSales(localDateTime);
//        for(BusinessSalesVO businessSalesVO:response){
//            System.out.println("businessSalesVO: " + businessSalesVO);
//        }

        // 票型销售统计
        List<TicketSalesVO> response = ticketSales(localDateTime);
        for(TicketSalesVO ticketSalesVOS:response){
            System.out.println("ticketSalesVOS: " + ticketSalesVOS);
        }
    }
}